package com.banshuibao.bsb_android.activity;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.banshuibao.bsb_android.Constants;
import com.banshuibao.bsb_android.R;
import com.banshuibao.bsb_android.http.HttpResponse;
import com.banshuibao.bsb_android.http.HttpUtil;
import com.banshuibao.bsb_android.model.AddressModel;
import com.banshuibao.bsb_android.model.ExpertRecorderDetailModel;
import com.banshuibao.bsb_android.model.ExpertTreeModel;
import com.banshuibao.bsb_android.model.RecorderContentModel;
import com.banshuibao.bsb_android.model.RecorderModel;
import com.banshuibao.bsb_android.model.RegionModel;
import com.banshuibao.bsb_android.model.RequestOkModel;
import com.banshuibao.bsb_android.util.ClearDirUtil;
import com.banshuibao.bsb_android.util.GetLoginInfo;
import com.banshuibao.bsb_android.util.IntentManager;
import com.banshuibao.bsb_android.util.MyEditText;
import com.banshuibao.bsb_android.util.SelectPopupWindowUtil;
import com.banshuibao.bsb_android.util.XToast;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class RecorderEditActivity extends BaseActivity implements View.OnClickListener {

    private RelativeLayout tax_type, topic_type, trad_type, areaId_type, areaId_tax_type, next;

    private MyEditText title, content, price;

    private TextView type_tv;

    private String questionUuid, recorder_title, recorder_content, recorder_price, voiceUuid;

    private String tax, taxUuid, topic, topicUuid, trade, tradeUuid, areaId, areaIdUuid, areaId_tax, areaId_taxUuid, type;

    private TextView tax_tv, trade_tv, topic_tv, areaId_tv, areaId_tax_tv;

    private RadioButton all_type, portion_type;

    private LinearLayout all_tag,portion_tag;

    private Context context;

    private String name;

    private boolean isRecord = false;

    private RecorderContentModel model;

    private RecorderModel recorderModel;

    private ExpertTreeModel expertTreeModel;
    private SelectPopupWindowUtil selectPopupWindowUtil;
    private PopupWindow popupWindow;
    private List<ExpertTreeModel.DataBean.ChildrenBean> tradeList;
    private List<ExpertTreeModel.DataBean.ChildrenBean> taxList;
    private List<ExpertTreeModel.DataBean.ChildrenBean> topicList;
    private List<AddressModel> list;

    private ExpertRecorderDetailModel.DataBean dataBean;
    private String role;
    private RelativeLayout price_layout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recorder_edit);
        role = GetLoginInfo.getLoginInfoInstance(this).readUser().getRole();
        context = this;
        model = new RecorderContentModel();
        recorderModel = new RecorderModel();
        list = new ArrayList<>();
        dataBean = (ExpertRecorderDetailModel.DataBean) getIntent().getSerializableExtra("bean");
        questionUuid = dataBean.getExpertQu().getUuid();
        getTreeData();
        initView();
        setData();
    }

    public void initView() {
        setTitleText("修改录音");
        trad_type = findViewById(R.id.trade_type);
        tax_type = findViewById(R.id.tax_type);
        topic_type = findViewById(R.id.topic_type);
        areaId_type = findViewById(R.id.areaId_type);
        areaId_tax_type = findViewById(R.id.areaId_tax_type);
        next = findViewById(R.id.next);
        title = findViewById(R.id.title);
        content = findViewById(R.id.content_et);
        price_layout = findViewById(R.id.price_layout);
        if(role.equals("2")||role.equals("3")){
            price_layout.setVisibility(View.VISIBLE);
        }else{
            price_layout.setVisibility(View.GONE);
        }
        price = findViewById(R.id.price_et);
        price.setFilters(new InputFilter[]{new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int i, int i1, Spanned dest, int i2, int i3) {
                if (source.equals(".") && dest.toString().length() == 0) {
                    return "0.";
                }
                if (dest.toString().contains(".")) {
                    int index = dest.toString().indexOf(".");
                    int length = dest.toString().substring(index).length();
                    if (length == 3) {
                        return "";
                    }
                }
                return null;
            }
        }});
        trade_tv = findViewById(R.id.trade);
        tax_tv = findViewById(R.id.tax);
        topic_tv = findViewById(R.id.topic);
        areaId_tv = findViewById(R.id.areaId);
        areaId_tax_tv = findViewById(R.id.areaId_tax);
        all_type = findViewById(R.id.title1);
        portion_type = findViewById(R.id.title2);
        all_tag = findViewById(R.id.all_tag);
        portion_tag = findViewById(R.id.portion_tag);
        trad_type.setOnClickListener(this);
        tax_type.setOnClickListener(this);
        topic_type.setOnClickListener(this);
        areaId_type.setOnClickListener(this);
        areaId_tax_type.setOnClickListener(this);
        next.setOnClickListener(this);
        all_type.setOnClickListener(this);
        portion_type.setOnClickListener(this);
        selectPopupWindowUtil = new SelectPopupWindowUtil(this);
        selectPopupWindowUtil.setContent(new SelectPopupWindowUtil.ItemOnClickListener() {
            @Override
            public void getContent(String name, String uuid) {
                if (popupWindow != null && popupWindow.isShowing()) {
                    popupWindow.dismiss();
                }
                if (name.equals("无")) {
                    name = "";
                }
                if(TextUtils.isEmpty(uuid)){
                    uuid = "00";
                }
                switch (type) {
                    case "trade":
                        trade = name;
                        tradeUuid = uuid;
                        trade_tv.setText(trade);
                        recorderModel.setTrade(tradeUuid);
                        model.setTrade_uuid(tradeUuid);
                        model.setTrade_type("trade");
                        model.setTrade_name(trade);
                        clearPortion();
                        break;
                    case "tax":
                        tax = name;
                        taxUuid = uuid;
                        tax_tv.setText(tax);
                        recorderModel.setTax(taxUuid);
                        model.setTax_uuid(taxUuid);
                        model.setTax_type("tax");
                        model.setTax_name(tax);
                        clearPortion();
                        break;
                    case "topic":
                        topic = name;
                        topicUuid = uuid;
                        topic_tv.setText(topic);
                        recorderModel.setTopic(topicUuid);
                        model.setTopic_uuid(topicUuid);
                        model.setTopic_type("topic");
                        model.setTopic_name(topic);
                        clearPortion();
                        break;
                    case "areaId":
                        areaId = name;
                        areaIdUuid = uuid;
                        areaId_tv.setText(areaId);
                        recorderModel.setAreaId(areaIdUuid);
                        model.setAreaId_uuid(areaIdUuid);
                        model.setAreaId_type("areaId");
                        model.setAreaId_name(areaId);
                        clearAll();
                        break;
                    case "areaId_tax":
                        areaId_tax = name;
                        areaId_taxUuid = uuid;
                        areaId_tax_tv.setText(areaId_tax);
                        recorderModel.setTax(areaId_taxUuid);
                        model.setAreaId_tax_uuid(areaId_taxUuid);
                        model.setAreaId_tax_type("areaId_tax");
                        model.setAreaId_tax_name(areaId_tax);
                        clearAll();
                        break;
                }

            }
        });
    }

    public void setData() {
        ExpertRecorderDetailModel.DataBean.ExpertQuBean expertQu = dataBean.getExpertQu();
        List<ExpertRecorderDetailModel.DataBean.ExpertVoicesBean> expertVoices = dataBean.getExpertVoices();
        title.setText(expertQu.getQuestion());
        if (expertVoices != null && expertVoices.size() > 0) {
            content.setText(expertVoices.get(expertVoices.size() - 1).getContent());
            voiceUuid = expertVoices.get(expertVoices.size() - 1).getUuid();
        }
        price.setText(String.valueOf(expertQu.getQuPrice()));
        String areaId = expertQu.getAreaId();
        String tax = expertQu.getTax();
        String topic = expertQu.getTopic();
        String trade = expertQu.getTrade();
        if (!TextUtils.isEmpty(areaId)) {
            areaId_tv.setText(areaId);
            areaId_tax_tv.setText(tax);
            portion_type.setChecked(true);
            all_tag.setVisibility(View.GONE);
            portion_tag.setVisibility(View.VISIBLE);
        }else {
            if (!TextUtils.isEmpty(tax)) {
                tax_tv.setText(tax);
                all_type.setChecked(true);
                all_tag.setVisibility(View.VISIBLE);
                portion_tag.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(topic)) {
                all_type.setChecked(true);
                topic_tv.setText(topic);
                all_tag.setVisibility(View.VISIBLE);
                portion_tag.setVisibility(View.GONE);
            }
            if (!TextUtils.isEmpty(trade)) {
                all_type.setChecked(true);
                trade_tv.setText(trade);
                all_tag.setVisibility(View.VISIBLE);
                portion_tag.setVisibility(View.GONE);
            }
        }
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.trade_type:
                type = "trade";
                showPopupWindows(view, tradeList, null, "tree");
                break;
            case R.id.tax_type:
                type = "tax";
                showPopupWindows(view, taxList, null, "tree");
                break;
            case R.id.topic_type:
                type = "topic";
                showPopupWindows(view, topicList, null, "tree");
                break;
            case R.id.areaId_type:
                type = "areaId";
                showPopupWindows(view, null, list, "");
                break;
            case R.id.areaId_tax_type:
                type = "areaId_tax";
                showPopupWindows(view, taxList, null, "tree");
                break;
            case R.id.title1:
                all_tag.setVisibility(View.VISIBLE);
                portion_tag.setVisibility(View.GONE);
                break;
            case R.id.title2:
                all_tag.setVisibility(View.GONE);
                portion_tag.setVisibility(View.VISIBLE);
                break;
            case R.id.next:
                showText();
                break;

        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (resultCode) {
            case RESULT_OK:
//                if (data != null) {
//                    AddressModel addressModel = (AddressModel) data.getSerializableExtra("type");
//                    typeUuid = addressModel.getUuid();
//                    name = addressModel.getName();
//                    type_tv.setText(name);
//                    parameter_type = addressModel.getParameter_type();
//                    model.setUuid(typeUuid);
//                    model.setParameter_type(parameter_type);
//                    switch (parameter_type) {
//                        case "industry":
//                            recorderModel.setTrade(typeUuid);
//                            break;
//                        case "category":
//                            recorderModel.setTax(typeUuid);
//                            break;
//                        case "special":
//                            recorderModel.setTopic(typeUuid);
//                            break;
//                        case "region":
//                            recorderModel.setAreaId(typeUuid);
//                            break;
//                    }
//                } else {
//                    XToast.showToast(context, "获取数据失败");
//                }
//                break;
            case 1002:
                setResult(RESULT_OK);
                finish();
                break;
        }

    }

    public void getData(boolean isRecord) {
        recorder_title = title.getText().toString().trim();
        recorder_content = content.getText().toString().trim();
        recorder_price = price.getText().toString().trim();
        String trade = trade_tv.getText().toString().trim();
        String tax = tax_tv.getText().toString().trim();
        String topic = topic_tv.getText().toString().trim();
        String areaId = areaId_tv.getText().toString().trim();
        String areaId_tax = areaId_tax_tv.getText().toString().trim();
//        Log.e("TAG", "getData:trade++++ "+trade+"uuid"+recorderModel.getTrade() );
//        Log.e("TAG", "getData:tax++++ "+tax+"uuid"+recorderModel.getTax());
//        Log.e("TAG", "getData:topic++++ "+topic+"uuid"+recorderModel.getTopic() );
//        Log.e("TAG", "getData:areaid++++ "+areaId+"uuid"+recorderModel.getAreaId() );
//        Log.e("TAG", "getData:areaId_tax++++ "+areaId_tax+"uuid"+recorderModel.getTax() );
        if (TextUtils.isEmpty(recorder_title)) {
            XToast.showToast(context, "请输入标题");
            return;
        } else if (TextUtils.isEmpty(recorder_content)) {
            XToast.showToast(context, "请输入录音文本");
            return;
        } else if(role.equals("2")||role.equals("3")) {
           if (TextUtils.isEmpty(recorder_price)) {
                XToast.showToast(context, "请输入问题价格");
                return;
            }else {
               double d = Double.valueOf(recorder_price);
               if (d == 0 || d < 1) {
                   XToast.showToast(context, "问题的价格要大于1元");
                   return;
               }
           }
        }
        if(TextUtils.isEmpty(trade)&&TextUtils.isEmpty(tax)&&TextUtils.isEmpty(topic)){
            if(TextUtils.isEmpty(areaId)&&TextUtils.isEmpty(areaId_tax)){
                XToast.showToast(RecorderEditActivity.this,"请选择语音类型");
                return;
            }else if(!TextUtils.isEmpty(areaId)&&TextUtils.isEmpty(areaId_tax)){
                XToast.showToast(RecorderEditActivity.this,"请选择地区税种类型");
                return;
            }else if(TextUtils.isEmpty(areaId)&&!TextUtils.isEmpty(areaId_tax)){
                XToast.showToast(RecorderEditActivity.this,"请选择地区类型");
                return;
            }
        }

        if (isRecord) {
            model.setAreaId_name(areaId);
            model.setAreaId_tax_name(areaId_tax);
            model.setTrade_name(trade);
            model.setTax_name(tax);
            model.setTopic_name(topic);
            model.setRecorder_content(recorder_content);
            model.setRecorder_price(recorder_price);
            model.setRecorder_title(recorder_title);
            model.setQuestionUuid(questionUuid);
            model.setVoiceUuid(voiceUuid);
            IntentManager.goResetRecorderVideoActivity(RecorderEditActivity.this, model);
        } else {
            recorderModel.setUuid(questionUuid);
            recorderModel.setAskPrice(Double.valueOf(recorder_price));
            recorderModel.setVoiceText(recorder_content);
            recorderModel.setContent(recorder_title);
            recorderModel.setVoiceId(voiceUuid);
            showProgressDialog();
            HttpUtil.doPost(Constants.Url.EXPERT_RECORDER_EDIT, recorderModel, new HttpResponse(this, RequestOkModel.class) {
                @Override
                public void onResult(Object obj) {
                    RequestOkModel requestOkModel = (RequestOkModel) obj;
                    XToast.showToast(context, "上传成功");
                    setResult(RESULT_OK);
                    finish();
                }

                @Override
                public void responseEnd() {
                    super.responseEnd();
                    cancelProgressDialog();
                }
            });
        }
    }

    public void getTreeData() {
        /**
         * 行业税种专题数据
         */
        HttpUtil.doPost(Constants.Url.EXPERT_TREE, null, new HttpResponse(this, ExpertTreeModel.class) {
            @Override
            public void onResult(Object obj) {
                expertTreeModel = (ExpertTreeModel) obj;
                List<ExpertTreeModel.DataBean> data = expertTreeModel.getData();
                for (int i = 0; i < data.size(); i++) {
                    if (data.get(i).getName().equals("行业")) {
                        tradeList = data.get(i).getChildren();
                    } else if (data.get(i).getName().equals("税种")) {
                        taxList = data.get(i).getChildren();
                    } else if (data.get(i).getName().equals("专题")) {
                        topicList = data.get(i).getChildren();
                    }
                }
            }
        });

        /**
         * 地区数据
         */
        HttpUtil.doPost(Constants.Url.EXPERT_ADDRESS, null, new HttpResponse(this, RegionModel.class) {
            @Override
            public void onResult(Object obj) {
                RegionModel regionModel = (RegionModel) obj;
                TreeMap<String, String> json = regionModel.getData();
                setAddress(json);
            }
        });
    }

    public void setAddress(TreeMap<String, String> hashMap) {
        //遍历集合得到业务id+名称
        for (TreeMap.Entry<String, String> entry : hashMap.entrySet()) {
            list.add(new AddressModel(entry.getValue(), entry.getKey(), ""));
        }

    }

    public void clearAll(){
        String trade_text = trade_tv.getText().toString().trim();
        String tax_text = tax_tv.getText().toString().trim();
        String topic_text = topic_tv.getText().toString().trim();
        if(!TextUtils.isEmpty(trade_text)){
            trade_tv.setText("");
            trade = "";
            tradeUuid="00";
        }
        if(!TextUtils.isEmpty(tax_text)){
            tax_tv.setText("");
            taxUuid="00";
            tax = "";
        }
        if(!TextUtils.isEmpty(topic_text)){
            topic_tv.setText("");
            topic = "";
            topicUuid = "00";
        }
        recorderModel.setTrade(tradeUuid);
        recorderModel.setTopic(topicUuid);
        model.setTrade_uuid(tradeUuid);
        model.setTopic_uuid(topicUuid);
        model.setTax_uuid(taxUuid);
    }

    public void clearPortion(){
       String areaId_text = areaId_tv.getText().toString().trim();
        if(!TextUtils.isEmpty(areaId_text)){
            areaId_tax_tv.setText("");
            areaId_tax= "";
            areaId_taxUuid="00";
            areaId = "";
            areaIdUuid = "00";
            areaId_tv.setText("");
        }
        recorderModel.setAreaId(areaIdUuid);
        model.setAreaId_uuid(areaIdUuid);
        model.setAreaId_tax_uuid(areaId_taxUuid);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ClearDirUtil.clearAll(new File(Constants.LocalFile.DIR));
        getSharedPreferences("record_reset", MODE_PRIVATE).edit().clear().commit();
    }

    /**
     * 查看文字
     */
    public void showText() {
        AlertDialog.Builder builder = new AlertDialog.Builder(context).setCancelable(true);  //先得到构造器
        builder.setTitle("提示"); //设置标题
        builder.setMessage("是否需要重新录音？"); //设置内容
        builder.setPositiveButton("不录，直接提交", new DialogInterface.OnClickListener() { //设置确定按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isRecord = false;
                getData(isRecord);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("重新录音", new DialogInterface.OnClickListener() { //设置取消按钮
            @Override
            public void onClick(DialogInterface dialog, int which) {
                isRecord = true;
                getData(isRecord);
                dialog.dismiss();
            }
        });
        //参数都设置完成了，创建并显示出来
        builder.create().show();
    }

    public void showPopupWindows(View view, List<ExpertTreeModel.DataBean.ChildrenBean> children, List<AddressModel> list, String tag) {
        popupWindow = selectPopupWindowUtil.getPopupWindow(children, list, tag);
        popupWindow.showAtLocation(view, Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); //设置layout在PopupWindow中显示的位置
    }
}
